// 基于准备好的dom，初始化echarts实例
let cale_pie = echarts.init(document.getElementById('cale'));
let cellSize = [90, 90];//每一小格大小
let pieRadius = 40;//饼图半径
let options;
//此处应该是从数据库默认读取当天的数据格式
let json = [];
let startDate = "2021-02-22";
let endDate = "2021-02-31";
let startMonth = "2021-02";
let endMonth = "2021-03";
let nowStatusMonth = startMonth;
let data_name = ['累计确诊', '累计治愈', '累计死亡'];//该出应该是从数据库中读取

getHistoryData();

function getHistoryData() {
    cale_pie.showLoading();
    $.ajax({
        type: 'get',
        url: '/getHistoryData',
        success: function (Hdata) {
            cale_pie.hideLoading();
            json = Hdata['cdata']['day'];
            startDate = Hdata['cdata']['startTime'];
            endDate = Hdata['cdata']['endTime'];
            startMonth = Hdata['cdata']['startMonth'];
            endMonth = Hdata['cdata']['endMonth'];
            console.log('已获取到历史数据');
            options = calendar(cellSize, pieRadius, startDate, endDate, json, data_name);
            cale_pie.setOption(options);
        }, error: function () {
            console.log("这个接口挂了");
        }
    })
}

function getMonth(handle) {//用于计算即将显示的月份
    let now_date = nowStatusMonth.split('-');
    let s = startMonth.split('-');
    let e = endMonth.split('-');
    let year = now_date[0];
    let month = now_date[1];
    let res_month;
    if (handle == 1) {
        if(parseInt(now_date[1]) == parseInt(e[1]) && now_date[0] == e[0]){
            alert('之后月份已无数据');
            return nowStatusMonth;
        }

        if (now_date[1] == '12') {
            year = (parseInt(now_date[0]) + 1).toString();
            month = "1";
        } else {
            month = (parseInt(now_date[1]) + 1).toString()
        }

    }

    if (handle == -1) {

        if(parseInt(now_date[1]) == parseInt(s[1]) && now_date[0] == s[0]){
            alert('之前月份已无数据');
            return nowStatusMonth;
        }

        if (now_date[1] == '01' || now_date[1] == '1') {
            year = (parseInt(now_date[0]) - 1).toString();
            month = "12";
        } else {
            month = (parseInt(now_date[1]) - 1).toString()
        }
    }
    res_month = year + '-' + month;
    console.log(res_month);
    return res_month;
}


//cellSize-----日历整体宽高
//pieRadius----日历饼图大小
//startDate----开始月份
//endDate------结束月份
//data---------数据集
//data_name----数据描述名称
function calendar(cellSize, pieRadius, startDate, endDate, json, data_name) {

    console.log("开始设置option");
    let data_arr = [];
    for (let i = 0; i < json.length; i++) {
        //console.log(json[i].data)
        data_arr.push(json[i].data);
    }

    //获取时间列表
    function getVirtulData() {
        let date = +echarts.number.parseDate(startDate);
        let end = +echarts.number.parseDate(endDate);
        let dayTime = 3600 * 24 * 1000;
        let data = [];
        for (let time = date; time <= end; time += dayTime) {
            data.push([
                echarts.format.formatTime('yyyy-MM-dd', time),
                Math.floor(Math.random() * 10000)//一个表示小于或等于指定数字的最大整数的数字。
            ]);
        }
        return data;
    }

    //创建饼图图形
    function getPieSeries(scatterData, chart) {
        return echarts.util.map(scatterData, function (item, index) {
            let center = chart.convertToPixel('calendar', item);

            return {
                id: index + 'pie',
                type: 'pie',
                center: center,
                label: {
                    normal: {
                        formatter: '{c}',
                        position: 'inside'
                    }
                },
                radius: pieRadius,
                data: data_arr[index]
            };
        });
    }


    // 使用刚指定的配置项和数据显示图表。
    function getPieSeriesUpdate(scatterData, chart) {
        return echarts.util.map(scatterData, function (item, index) {
            let center = chart.convertToPixel('calendar', item);
            return {
                id: index + 'pie',
                center: center
            };
        });
    }

    let scatterData = getVirtulData();

    let option = {
        tooltip: {},
        color:[	'#8B0000', '#006400', '#000000'],
        legend: {
            orient: 'vertical',
            data: data_name,
            bottom: 20,
            top:'0',
            left: 'left'
        },
        title:{
            text: nowStatusMonth.split('-')[0]+'年'+parseInt(nowStatusMonth.split('-')[1]).toString()+'月病患类型比例',
            top: 'auto',
            left: '40%'
        },
        calendar: {
            top: '15%',
            left: 'center',
            orient: 'vertical',
            cellSize: cellSize,
            yearLabel: {
                show: false,
                textStyle: {
                    fontSize: 30
                }
            },
            dayLabel: {
                margin: 20,
                firstDay: 1,
                nameMap: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
            },
            monthLabel: {
                show: false
            },
            range: [nowStatusMonth]
        },
        toolbox: {//工具箱，包含一些图标的可执行操作
            show: true,
            orient: 'horizontal',
            itemSize: 20,
            top: '0',
            left: '80%',
            itemGap: 15,
            feature: {
                mytool_lastM: { //切换到上个月
                    show: true,
                    title: '上个月',
                    icon: 'image://static\\image\\last.png',
                    onclick: function () {
                        cale_pie.showLoading();
                        nowStatusMonth = getMonth(-1);
                        let show_other = calendar(cellSize, pieRadius, startDate, endDate, json, data_name);
                        cale_pie.setOption(show_other);
                        cale_pie.hideLoading();
                    }
                },
                mytool_nextM: { //切换到下个月
                    show: true,
                    title: '下个月',
                    icon: 'image://static\\image\\next.png',
                    onclick: function () {
                        cale_pie.showLoading();
                        nowStatusMonth = getMonth(1);
                        let show_other = calendar(cellSize, pieRadius, startDate, endDate, json, data_name);
                        cale_pie.setOption(show_other);
                        cale_pie.hideLoading();
                    }
                },
                saveAsImage: {show: true, title: '保存图片'}

            }
        },
        series: [{
            id: 'label',
            type: 'scatter',
            coordinateSystem: 'calendar',
            symbolSize: 1,
            label: {
                normal: {
                    show: true,
                    formatter: function (params) {
                        return echarts.format.formatTime('dd', params.value[0]);
                    },
                    offset: [-cellSize[0] / 2 + 10, -cellSize[1] / 2 + 10],
                    textStyle: {
                        color: '#000',
                        fontSize: 14
                    }
                }
            },
            data: scatterData
        }]
    };

    if (!cale_pie.inNode) {
        let pieInitialized;
        setTimeout(function () {
            pieInitialized = true;
            cale_pie.setOption({
                series: getPieSeries(scatterData, cale_pie)
            });
        }, 10);

        cale_pie.onresize = function () {
            if (pieInitialized) {
                cale_pie.setOption({
                    series: getPieSeriesUpdate(scatterData, cale_pie)
                });
            }
        };
    }
    return option;
}

window.onresize=function(){
   cale_pie.resize();
};